package main

import (
	pb "learngo/consignment-service/proto/consignment"
	microclient "github.com/micro/go-micro/client"
	"io/ioutil"
	"encoding/json"
	"log"
	"os"
	"context"
	"github.com/micro/go-micro/cmd"
	"github.com/micro/go-micro/metadata"
)

const (
	address = "localhost:50051"
	defaultFilename = "consignment.json"
)

func ParseFile(file string)(*pb.Consignment, error)  {
	var consignment *pb.Consignment
	data,err := ioutil.ReadFile(file)

	if err != nil {
		return nil,err
	}
	json.Unmarshal(data,&consignment)
	return consignment,err
}


func main() {

	cmd.Init()

	// 创建微服务的客户端，简化了手动 Dial 连接服务端的步骤
	client := pb.NewShippingServiceClient("go.micro.srv.consignment", microclient.DefaultClient)


	// 在命令行中指定新的货物信息 json 件
	if len(os.Args) < 3 {
		log.Fatalln("Not enough arguments, expecing file and token.")
	}

	infoFile := os.Args[1]
	token := os.Args[2]

	// 解析货物信息
	consignment, err := ParseFile(infoFile)
	if err != nil {
		log.Fatalf("Could not parse file: %v", err)
	}

	// 创建带有用户 token 的 context
	// consignment-service 服务端将从中取出 token，解密取出用户身份
	tokenContext := metadata.NewContext(context.Background(),map[string]string{
		"token": token,
	})

	// 调用 RPC
	// 将货物存储到指定用户的仓库里
	r,err := client.CreateConsignment(tokenContext,consignment)
	if err != nil {
		log.Fatalf("Could not greet: %v", err)
	}

	log.Printf("Created: %t", r.Created)


	// 列出目前所有托运的货物
	getAll, err := client.GetConsignments(context.Background(), &pb.GetRequest{})
	if err != nil {
		log.Fatalf("Could not list consignments: %v", err)
	}
	for _, v := range getAll.Consignments {
		log.Println(v)
	}


}
